package demo.security.example.web;

import com.fasterxml.jackson.annotation.JsonView;
import demo.security.example.model.dto.UserQueryCondition;
import demo.security.example.model.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * UserController
 *
 * @author lidj
 * @date 2018-01-08
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @PostMapping("/regist")
    public void regist(User user,HttpServletRequest request) {
        //不管是注册用户还是绑定用户，都会拿到一个用户唯一标识。
        String userId = user.getUserName();
        providerSignInUtils.doPostSignUp(userId, new ServletWebRequest(request));
    }

    @PostMapping
    public User create(@Valid @RequestBody  User user, BindingResult errors){

        if (errors.hasErrors()){
           errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }

        System.out.println(user.getUserName());
        System.out.println(user.getPassWord());
        System.out.println(user.getBirthday());

        user.setUserId("1");
        return user;
    }

    @PutMapping("/{userId:\\d+}")
    public User update(@Valid @RequestBody  User user, BindingResult errors){
        System.out.println("update test");
        if (errors.hasErrors()){
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }
        System.out.println(user.getUserName());
        System.out.println(user.getPassWord());
        System.out.println(user.getBirthday());

        user.setUserId("1");
        return user;
    }

    @DeleteMapping("/{userId:\\d+}")
    public void delete(@PathVariable String userId){
      System.out.println(userId);
    }

    @GetMapping
    @JsonView(User.UserSimpleView.class)
    public List<User> query(UserQueryCondition userQueryCondition){
        List<User> list = new ArrayList<>();
        list.add(new User());
        list.add(new User());
        list.add(new User());
        return list;
    }

    @GetMapping(value = "/{userId:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable String userId){
        System.out.println("进入getInfo服务");
        User user = new User();
        user.setUserName("tom");
        return user;
      // throw new UserNotExistsException(userId);
    }



}
